;(function() {
	'use strict';

	angular.module('controllers.omdisplay.sysBusStat')
		.controller('sbsSumStatisticsCtrl', sumStatisticsCtrl);
	/**
	 * [sumStatisticsCtrl]
	 * 业务线:
	 * businessLineCode: '1'--->businessLineName:'天猫旗舰店'
	 * businessLineCode: '2'--->businessLineName:'银行总对总'
	 * businessLineCode: '3'--->businessLineName:'移动商城'
	 * businessLineCode: '4'--->businessLineName:'灵犀语音'
	 * businessLineCode: '5'--->businessLineName:'有价卡'
	 */
	function sumStatisticsCtrl($scope, sumstatistics, $timeout, CoreService, COREDATA) {
		var year, month, day; //给定默认的时间
		$scope.pageBind = {
			timeTypes: COREDATA.TIMETYPES, //帐期数据
			provinces: COREDATA.PROVINCES, //省份
			businessLine: COREDATA.BUSINESSLINE //业务线
		};
		//机构
		$scope.agencyData = sumstatistics.sumStatisticsServe.queryAgency();
		//状态数据
		$scope.tradeStates = sumstatistics.sumStatisticsData.getTradeState();
		//页面绑定对象
		$scope.sendData = sumstatistics.sumStatisticsData.getPageBindObj();
		//获取页面下拉框名字
		$scope.getNames = sumstatistics.sumStatisticsFn.getNames;
		//控制查询条件拉上拉下   1为拉下  0 为拉上
		$scope.shoumun = {
			num: 1
		};
		//控制等待样式   false 为隐藏   true 为显示
		$scope._loading.show = false;

		//根据不同的业务线,置灰对应的下拉框
		$scope.close = {
			organization: false,
			tradeType: false,
			channel: false
		};
		/**
		 * @function [getCloseState]单击业务线按钮，如果业务线为全部，将接入渠道,交易类型,机构下拉框全部置灰.如
		 * 果业务线为天猫或者移动商城,将接入渠道和机构置灰,如果业务线为银行总对总,下拉框全部不置灰,并且
		 * 根据选择的业务线查询出相应的交易类型
		 */
		$scope.getBL = function() {
			$timeout(function() {
				var bl = {
					businessLine: []
				};
				if ($scope.sendData.businessLine !== undefined) {
					bl.businessLine.push($scope.sendData.businessLine.businessLineCode);
				}
				if (bl.businessLine.length !== 0) {
					bl.businessLine.indexOf('2') !== -1 ? $scope.close.organization = true : $scope.close.organization = false;
					sumstatistics.sumStatisticsServe.queryTradeType(bl, function(res) {
						if(res.data.length !== 0){
							$scope.tradeTypes = res.data;
							$scope.close.tradeType = true;
						}
					});
					sumstatistics.sumStatisticsServe.queryChannels(bl, function(res) {
						if (res.data.length === 0) {
							$scope.close.channel = false;
						} else {
							$scope.accessChannels = res.data;
							$scope.close.channel = true;
						}
					});
				} else {
					$scope.close.organization = false;
					$scope.close.tradeType = false;
					$scope.close.channel = false;
				}
			});
			$scope.sendData.channel = [];
			$scope.sendData.organization = [];
			$scope.sendData.tradeTypeCode = [];
		};
		$scope.diffTime = '不分时刻';
		//省份下拉框是否显示'全部(分省)'选项 true 显示  false 不显示
		$scope.showPro = true;
		//切换分时刻状态  如果分时刻就不分省 如果分省，就不分时刻
		$scope.changeDiffTime = function() {
			if ($scope.sendData.diffTime) {
				$scope.diffTime = '分时刻';
				$scope.showPro = false;
				$scope.pro = '全部(汇总)';
				$scope.sendData.diffPro = '1'; //分时刻下不分省 '1'为汇总 '2'为分省
			} else {
				$scope.diffTime = '不分时刻';
				$scope.showPro = true;
			}
		};
		year = new Date().getFullYear();
		month = new Date().getMonth();
		day = new Date().getDate() - 1;
		//监控帐期，选择不同的帐期，给开始时间和结束时间不同的默认值
		$scope.$watch('sendData.timeType', function(newValue) {
			switch (newValue) {
				case '5':
					$scope.sendData.startTime = year;
					$scope.sendData.endTime = year;
					break;
				case '4':
					$scope.sendData.startTime = '';
					$scope.sendData.endTime = '';
					break;
				case '3':
					$scope.sendData.startTime = new Date(year, month);
					$scope.sendData.endTime = new Date(year, month);
					break;
				case '1':
					$scope.sendData.startTime = new Date(year, month, day);
					$scope.sendData.endTime = new Date(year, month, day);
			}
		});
		//省份下拉框默认选项
		$scope.pro = '全部(汇总)';
		/**
		 * @function [provinceCheckAll] 省份选择'全部(汇总)'或'全部(分省)'
		 * @param {[string]} propertyName  省份code
		 * @param  {[object]} series   页面表单绑定的对象
		 * @param  {[string]} proName   省份下拉框前两个选项 '全部(汇总)'和'全部(分省)'
		 */
		$scope.provinceCheckAll = function(series, propertyName, proName) {
			$timeout(function   () {
				series[propertyName] = [];
				$scope.pro = proName;
				proName === '全部(分省)' ? $scope.sendData.diffPro = '2' : $scope.sendData.diffPro = '1';
			});
		};
		$scope.btnDisabled = true;
		$scope.showArrow = false;

		//监听表单
		$scope.$watch('myForm.$invalid', function(newValue) {
			newValue ? $scope.btnDisabled = true : $scope.btnDisabled = false;
		});
		////查询结果页面绑定对象
		$scope.send = {};
		//查询
		$scope.search = function() {
			if ($scope.shoumun.num === 1) {
				$scope.shoumun.num = 1;
				return;
			}
			var send;
			send = sumstatistics.sumStatisticsData.getSendData($scope.sendData);
			//分省状态
			send.diffPro === '2' ? $scope.proState = true : $scope.proState = false;
			//下钻时需要用到的状态值
			$scope.state = send.timeType;
			angular.copy(send, $scope.send);
			queryShowResult($scope.send);
			$scope.shoumun.num = 1;
			$scope._loading.show = true;
		};

		//导出路径
		$scope.formPrefix = COREDATA.FORMPREFIX + 'Omdisplay/sysBusinessStatistics/exportExcel';

		var keep = {
			tableData: [], //每次下钻保存的当前页面表格的数据
			viewData: [], //每次下钻保存的当前页面图形的数据
			condition: [], //保存每次查询的条件
			sum: [], //保存交易状态为全部时汇总的数据
			title: [] //保存的标题
		};
		//是否点击了返回按钮 true 是  false 否   当点击返回按钮时点击导出时修改查询条件
		var backState = false;
		//区分是否是第一次查询，如果是第一次查询，那么页面显示排序样式，否则下钻后不显示排序样式
		$scope.firstQuery = false;
		var myEcharts = echarts.init(document.getElementById('doc'));

		function queryShowResult(send) {
			keep = {
				tableData: [],
				viewData: [],
				condition: [],
				sum: [],
				title: []
			};
			$scope.showBack = false;
			var conditionSend = {};
			send.title = sumstatistics.sumStatisticsFn.getTitle(send);
			sumstatistics.sumStatisticsServe.querySumStatistics(send, function(result) {
				if (result.state === '10000' && result.data.length >= 1) {
					$scope.showArrow = true;
					$scope.title = send.title;
					$scope.avgName = sumstatistics.sumStatisticsFn.getAvgName(send, $scope.proState);
					angular.copy(send, conditionSend);
					keep.condition.push(conditionSend);
					keep.title.push($scope.title);
					backState = false;
					showQueryResult(send, result);
					$scope.firstQuery = true;
				} else if (result.data.length === 0) {
					$scope.shoumun.num = 1;
					$scope.showArrow = false;
					$scope.flag = '';
					$scope._loading.show = false;
					CoreService.dialog('查询无数据');
				} else {
					$scope.shoumun.num = 1;
					$scope.showArrow = false;
					$scope.flag = '';
					$scope._loading.show = false;
					CoreService.dialog('查询错误');
				}
			});
		}
		//省公司排序
		$scope.showSeq = true;
		$scope.proSeq = function(type) {
			if ($scope.send.diffTime === 'true' || $scope.send.diffPro === '1') {
				return;
			}
			$scope.showSeq = !$scope.showSeq;
			sumstatistics.sumStatisticsFn.mySort($scope.showSeq, type, 'provinceCode');
		};
		//业务量排序
		$scope.seqBus = true;
		$scope.diffBusNum = function(type) {
			if ($scope.send.diffTime === 'true') {
				return;
			}
			$scope.seqBus = !$scope.seqBus;
			sumstatistics.sumStatisticsFn.mySort($scope.seqBus, type, 'businessNum');
		};
		/**
		 * @function [depDown] 单击表格行下钻
		 * @param  {[object]} downData 页面单击表格时的行对象
		 */
		$scope.depDown = function(downData) {
			$scope._loading.show = true;
			//已经下钻到了最底层
			if ($scope.send.diffTime === 'true' || $scope.send.timeType === 't') {
				$scope._loading.show = false;
				// CoreService.dialog('下钻无数据');
				return;
			}
			if ($scope.shoumun.num === 1) {
				$scope.shoumun.num = 0;
			}
			var typeDown = $scope.send.timeType;
			$scope.send.provinceCode = [];
			//在分省情况下,保留点击下钻时的省份
			if ($scope.send.diffPro === '2') {
				$scope.send.provinceCode.push(downData.provinceCode);
			} else {
				//由于分省时下钻过后变成了不分省,但是页面还是需要显示下钻时的省份,所以每次还是要保存下钻时省份
				//的code,但页面省份名字为'全部'时,代表省份汇总,此情况下不需要保存省份code
				if (downData.provinceName !== '全部') {
					$scope.send.provinceCode.push(downData.provinceCode);
				}
			}
			//改变下钻的timetype
			sumstatistics.sumStatisticsFn.fmtDown(downData, $scope.send);
			if ($scope.send.diffPro === '2') {
				$scope.send.timeType = typeDown;
				$scope.send.diffPro = '1';
			}
			var conditionSend = {};
			//获取均值名称
			var avgName = sumstatistics.sumStatisticsFn.getAvgName($scope.send, $scope.proState);
			$scope.send.avg = avgName;
			angular.copy($scope.send, conditionSend);
			keep.condition.push(conditionSend);
			backState = false;
			$scope.send.title = sumstatistics.sumStatisticsFn.getTitle($scope.send);
			sumstatistics.sumStatisticsServe.querySumStatistics($scope.send, function(result) {
				if (result.state === '10000' && result.data.length >= 1) {
					$scope.avgName = avgName;
					$scope.title = $scope.send.title;
					keep.title.push($scope.title);
					showQueryResult($scope.send, result);
					$scope.showBack = true;
					$scope.firstQuery = false;
				} else if (result.data.length === 0) {
					$scope._loading.show = false;
					CoreService.dialog('查询无数据');
				} else {
					$scope._loading.show = false;
					CoreService.dialog('查询错误');
				}
			});
		};
		/**
		 * @function [showQueryResult] 显示的查询结果,当交易状态为全部的时候,区分业务量,订单金额,
		 * 充值金额
		 * @param  {[object]} send   查询条件
		 * @param  {[object]} result 查询结果
		 */
		function showQueryResult(send, result) {
			$scope.sumTotal = [0, 0, 0, 0, 0, 0, 0, 0, 0];
			$scope.items = [];
			$scope.sumItems = [];
			var secharts = {};
			var timeXDataArr = [];
			//给每个省份相应的code
			sumstatistics.sumStatisticsFn.giveProCode(send, result, $scope.pageBind.provinces);
			myEcharts.clear();
			//区分交易状态
			if (send.tradeStateCode.length === 0) {
				//汇总
				$scope.sumTotal = sumstatistics.sumStatisticsFn.getCollect(result);
				//订单金额和充值金额取后两位小数(四舍五入)
				for (var s = 3,i = $scope.sumTotal.length; s < i; s++) {
					$scope.sumTotal[s] = $scope.sumTotal[s].toFixed(2);
				}
				$scope.items = result.data;
				keep.tableData.push($scope.items);
				secharts = sumstatistics.sumStatisticsFn.getEchartsData(send, $scope.items);
				$scope.sum = sumstatistics.sumStatisticsFn.calculateSummary($scope.items);
				$scope.flag = 'table1';
			} else {
				$scope.sumItems = result.data;
				keep.tableData.push($scope.sumItems);
				secharts = sumstatistics.sumStatisticsFn.getEchartsData(send, $scope.sumItems);
				$scope.sum = sumstatistics.sumStatisticsFn.calculateSummary($scope.sumItems);
				$scope.flag = 'table';
			}
			myEcharts.setOption(secharts);
			$timeout(function() {
				$scope.outData = sumstatistics.sumStatisticsFn.exportView(backState, myEcharts, send, $scope.sendOut);
			});
			//均值
			$scope.avgSumBusinessNum = result.avgSumBusinessNum.toFixed(2);
			$scope.avgSumOrderAmount = result.avgSumOrderAmount.toFixed(2);
			$scope.avgSumRechargeAmount = result.avgSumRechargeAmount.toFixed(2);
			//下钻保存的均值
			timeXDataArr.push($scope.avgSumBusinessNum);
			timeXDataArr.push($scope.avgSumOrderAmount);
			timeXDataArr.push($scope.avgSumRechargeAmount);
			keep.sum.push($scope.sumTotal);
			keep.viewData.push(timeXDataArr);
			$scope.shoumun.num = 0;
			$scope._loading.show = false;
			$scope.channel = $scope.close.channel; //渠道
			$scope.organization = $scope.close.organization; //机构
			$scope.tradeType = $scope.close.tradeType; //类型
		}
		//切换到表格
		$scope.changeTable = function() {
			$scope.send.tradeStateCode.length === 0 ? $scope.flag = 'table1' : $scope.flag = 'table';
		};
		//切换到图形
		$scope.changeView = function() {
			$scope.flag = 'view';
		};
		/**
		 * @function [back] 单击返回按钮,日-->日汇总-->月-->季-->年-->分省
		 */
		$scope.sendOut = {};
		$scope.back = function() {
			backState = true;
			var secharts = {};
			keep.condition.pop();
			$scope.sendOut = keep.condition[keep.condition.length - 1];
			var type = $scope.send.timeType;
			var timeXDataArr = [];
			keep.tableData.pop();
			keep.viewData.pop();
			keep.sum.pop();
			keep.title.pop();
			$scope.title = keep.title[keep.title.length - 1];
			$scope.send.title = $scope.title;
			$scope.sumTotal = [];
			if ($scope.send.tradeStateCode.length === 0) {
				$scope.items = keep.tableData[keep.tableData.length - 1];
				$scope.sumTotal = keep.sum[keep.sum.length - 1];
			} else {
				$scope.sumItems = keep.tableData[keep.tableData.length - 1];
			}
			timeXDataArr = keep.viewData[keep.viewData.length - 1];
			$scope.avgSumBusinessNum = timeXDataArr[0];
			$scope.avgSumOrderAmount = timeXDataArr[1];
			$scope.avgSumRechargeAmount = timeXDataArr[2];
			$scope.send.timeType = sumstatistics.sumStatisticsFn.getTimeType(type);
			if (keep.tableData.length === 1) {
				$scope.showBack = false;
				$scope.firstQuery = true;
				$scope.send.timeType = $scope.state;
			}
			if ($scope.proState && keep.tableData.length === 1) {
				$scope.send.diffPro = '2';
			}
			myEcharts.clear();
			if ($scope.send.tradeStateCode.length === 0) {
				secharts = sumstatistics.sumStatisticsFn.getEchartsData($scope.send, $scope.items);
				$scope.sum = sumstatistics.sumStatisticsFn.calculateSummary($scope.items);
			} else {
				secharts = sumstatistics.sumStatisticsFn.getEchartsData($scope.send, $scope.sumItems);
				$scope.sum = sumstatistics.sumStatisticsFn.calculateSummary($scope.sumItems);
			}
			myEcharts.setOption(secharts);
			$scope.avgName = sumstatistics.sumStatisticsFn.getAvgName($scope.send, $scope.proState);
			$timeout(function() {
				$scope.outData = sumstatistics.sumStatisticsFn.exportView(backState, myEcharts, $scope.send, $scope.sendOut);
			});
		};
	}
	sumStatisticsCtrl.$inject = ['$scope', 'sumstatistics', '$timeout', 'CoreService', 'COREDATA'];
})();